<template>
  <div>
    <div class="user-root">
      <!--左侧部门-->
      <div>
        <el-tree
          :data="state.treeData"
          :props="treeProps"
          :default-expand-all="true"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        />
      </div>
      <!--右侧数据-->
      <div>
        <el-form :inline="true" :model="state.pages" class="demo-form-inline">
          <el-form-item label="用户名">
            <el-input
              v-model="state.pages.userName"
              placeholder="请输入用户名"
            />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input
              v-model="state.pages.phonenumber"
              placeholder="请输入用户名"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="state.pages.status" placeholder="请输入用户名">
              <el-option
                v-for="item in state.statusList"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8 btns">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd">
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDelete">
              删除
            </el-button>
          </el-col>
        </el-row>

        <el-table
          :data="state.tableData"
          :header-cell-style="{ background: exCss.primaryColor, color: '#fff' }"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="userId" label="用户编号" />
          <el-table-column prop="userName" label="用户名称" />
          <el-table-column prop="nickName" label="用户昵称" />
          <el-table-column prop="dept.deptName" label="部门" />
          <el-table-column prop="phonenumber" label="手机号码" />
          <el-table-column label="状态">
            <template #default="scope">
              <el-tag
                v-if="scope.row.status === '1'"
                class="ml-2"
                type="danger"
              >
                停用
              </el-tag>
              <el-tag
                v-if="scope.row.status === '0'"
                class="ml-2"
                type="success"
              >
                正常
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column label="操作" width="300">
            <template #default="scope">
              <el-button
                text
                type="primary"
                icon="Edit"
                style="width: 50px"
                @click="rowUpdateUser(scope.row)"
              >
                修改
              </el-button>
              <el-button
                text
                type="primary"
                icon="Delete"
                style="width: 50px"
                @click="rowRemoveUser(scope.row)"
              >
                删除
              </el-button>
              <el-button
                text
                type="primary"
                icon="RefreshRight"
                style="width: 80px"
                @click="refreshPwd(scope.row)"
              >
                重置密码
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-block">
          <el-pagination
            v-model:currentPage="state.pages.pageNum"
            v-model:page-size="state.pages.pageSize"
            background
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="state.pages.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <!--添加/修改用户弹框-->
    <user-dialog
      ref="userEl"
      :is-add="state.isAdd"
      :title="state.isAdd ? '新增用户' : '修改用户'"
      :dialog-visible="state.isShow"
      @close="close"
    />
    <!--重置密码弹框-->
    <reset-pwd
      @close="() => (state.reset.pwdShow = false)"
      :dialog-visible="state.reset.pwdShow"
      :user-id="state.reset.userId"
      :user-name="state.reset.userName"
    />
  </div>
</template>

<script setup>
import exCss from '@/style/module/primary.module.scss'
import { delUser, deptTreeSelect, getUser, listUser } from '@/api/user/index'
import UserDialog from '@/view/system/component/UserDialog.vue'
import ResetPwd from '@/view/system/component/ResetPwd.vue'

const userEl = ref()
const treeProps = {
  children: 'children',
  label: 'label',
}
const state = reactive({
  pages: {
    pageNum: 1,
    pageSize: 10,
    total: 0,
    userName: '',
    status: '',
    phonenumber: '',
    deptId: '',
  },
  isShow: false,
  isAdd: false,
  tableData: [],
  tabSelect: [],
  statusList: [
    { value: '0', label: '正常' },
    { value: '1', label: '停用' },
  ],
  reset: {
    pwdShow: false,
    userId: '',
  },
})

onMounted(() => {
  onSearch()
  getTreeData()
})
// 改变条数
const handleSizeChange = (e) => {
  state.pages.pageSize = e
  getData()
}
// 页码
const handleCurrentChange = (e) => {
  state.pages.pageNum = e
  getData()
}
// 查询
const onSearch = () => {
  state.pages.pageNum = 1
  getData()
}
// 重置
const onReset = () => {
  state.pages = {
    pageNum: 1,
    pageSize: 10,
    total: 0,
    userName: '',
    status: '',
    phonenumber: '',
    deptId: '',
  }
  onSearch()
}
// 公用的查询方法
const getData = () => {
  listUser(state.pages).then((res) => {
    state.tableData = res.rows
    state.pages.total = res.total
  })
}
// 查询部门树形结构
const getTreeData = () => {
  deptTreeSelect().then((res) => {
    state.treeData = res.data
  })
}
// 点击某个部门
const handleNodeClick = (node) => {
  state.pages.deptId = node.id
  onSearch()
}
// 表格选中触发
const handleSelectionChange = (val) => {
  state.tabSelect = val
  console.log(state.tabSelect)
}
// 关闭弹框
const close = (type) => {
  if (type) onSearch()
  state.isShow = false
}
// 按钮组-新增
const handleAdd = () => {
  getUser().then((res) => {
    state.isAdd = true
    state.isShow = true
    nextTick(() => {
      userEl.value.setFormData(null, res.roles)
    })
  })
}
// 按钮组-删除
const handleDelete = () => {
  if (state.tabSelect.length === 0) {
    ElMessage.error('请至少选择一项再进行删除')
    return
  }
  const userId = state.tabSelect.map((item) => item.userId).join(',')
  rowRemoveUser({ userId })
}
// 行按钮-修改
const rowUpdateUser = (row) => {
  // 先查询该用户详情
  getUser(row.userId).then((res) => {
    // 这个用户的当前角色
    row['roleIds'] = res.roleIds
    state.isAdd = false
    state.isShow = true
    nextTick(() => {
      userEl.value.setFormData(row, res.roles)
    })
  })
}
// 行按钮-删除
const rowRemoveUser = ({ userId }) => {
  ElMessageBox.confirm('确认删除该用户吗', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    delUser(userId).then((res) => {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      onSearch()
    })
  })
}
// 重置密码
const refreshPwd = (row) => {
  state.reset.pwdShow = true
  state.reset.userId = row.userId
  state.reset.userName = row.userName
}
</script>

<style scoped lang="scss">
.pagination-block {
  margin-top: 10px;
  float: right;
}

.user-root {
  display: flex;
  gap: 20px;
  width: 100%;
  min-height: 100%;

  & > div:nth-child(1) {
    width: 230px;
    min-height: 100%;
    border-right: 1px solid var(--el-color-primary-light-8);
  }

  & > div:nth-child(2) {
    flex: 1;
  }
}

.btns {
  margin-bottom: 10px;
}
</style>
